<template>
  <div class="page-login">
    <vue2-water-marker text="爆米花小布,后台管理系统"></vue2-water-marker>
    <div class="box">
      <div class="logo">
        <img src="@/assets/imgs/xiaobu-logo.png" alt="Logo" />
        <span>XIAOBU-ADMIN</span>
      </div>
      <p class="desc">一款vue2+vuex+element的后台管理系统</p>

      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-position="top" class="form"
        :disabled="loading">
        <el-form-item label="手机号" prop="userName">
          <input v-model.trim="loginForm.userName" placeholder="请输入手机号" maxlength="20"
            @blur="handleValidate('userName')" autocomplete="on" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <input v-model.trim="loginForm.password" type="password" placeholder="请输入密码" maxlength="20"
            @blur="handleValidate('password')" autocomplete="off" />
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <div class="row">
            <input v-model.trim="loginForm.code" @blur="handleValidate('code')" placeholder="图片验证码" maxlength="4" />

            <img v-if="captchaImg" ref="captchaRef" class="captcha-code" :src="captchaImg" @click="getCaptcha" alt="" />
          </div>
        </el-form-item>
        <el-link type="primary" @click="showRegister = true">没有账号，点击注册</el-link>
        <el-checkbox class="fr keep-login" v-model="keepLogin" @change="handleKeepLoginChange">保持登录</el-checkbox>
        <div class="op">
          <el-button round :loading="loading" @click.native.prevent="handleLogin">登录</el-button>
        </div>
      </el-form>
    </div>

    <register-dialog ref="register" title="注册用户" width="666px" :visible.sync="showRegister"
      @close="showRegister = false" :modal-append-to-body="false" :append-to-body="false"
      :close-on-click-modal="false"></register-dialog>
  </div>
</template>
<script>
import { MD5 } from "crypto-js"
import { commonApi } from "@/api"
import store from "@/store"
import registerDialog from "./components/register-dialog.vue"
export default {
  components: {
    registerDialog
  },
  data() {
    return {
      keepLogin: localStorage.getItem("keepLogin") === "1", // 是否保持登录
      showRegister: false, // 展示注册弹框
      captchaImg: null, // 图形验证码
      loading: false,
      loginForm: {
        userName: "",
        password: "",
        captchaId: "",
        code: ""
      },
      captchaForm: {
        id: "",
        imageBase64: ""
      },
      loginRules: {
        userName: [
          { required: true, message: "请输入手机号", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      },
      redirect: null
    }
  },
  watch: {
    showRegister(val) {
      if (!val) {
        this.$nextTick(() => {
          this.$refs.register.resetDialogForm()
        })
      } else {
        this.$modal.alertWarning("温馨提示：注册后将使用手机号进行登录，默认密码为【888888】")
      }
    }
  },
  created() {
    this.redirect = this.$route.query?.redirect
    window.addEventListener("keyup", this.login)
    //清除键盘监听事件
    this.$once("hook:beforeDestroy", () => {
      window.removeEventListener("keyup", this.login)
    })
    this.getCaptcha()
  },
  methods: {
    handleValidate(field) {
      this.$refs.loginFormRef.validateField(field)
    },
    // 是否保持登录改变事件
    handleKeepLoginChange(val) {
      this.$store.commit("user/SET_KEEP_LOGIN", val ? "1" : "0")
    },
    // 获取图形验证码
    getCaptcha() {
      commonApi.getCaptcha().then((data) => {
        this.captchaImg = data.base64SVG
        this.loginForm.captchaId = data.captchaId
      })
    },
    /**
     * @description: 键盘登录
     * @param {type}
     * @return {type}
     * @author: syx
     */
    login(e) {
      //防止重复回车
      if (this.loading) {
        return
      }
      // 兼容FF和IE和Opera
      var event = e || window.event
      var key = event.which || event.keyCode || event.charCode
      if (key === 13) {
        /*Do something. 调用一些方法*/
        this.handleLogin()
      }
    },
    // 点击登录
    handleLogin() {
      this.$refs.loginFormRef.validate((valid) => {
        if (valid) {
          this.loading = true
          const form = { ...this.loginForm }
          form.password = form.password && MD5(form.password).toString()
          commonApi
            .login(form)
            .then(async data => {
              await store.dispatch("user/setToken", data)
              this.$modal.msgSuccess("登录成功")
              this.loading = false
              this.$router.push({ path: this.redirect || "/" })
            })
            .catch((err) => {
              if (err?.name === "CanceledError") {
                return
              }
              this.getCaptcha()
              this.loading = false
            })
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.page-login {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100%;
  padding: 20px 0;
  width: 100%;
  position: relative;
  background-color: #2f3447;

  .box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .logo {
      height: 50px;
      margin-bottom: 30px;
      display: flex;
      align-items: center;
      color: #fff;

      img {
        height: 50px;
      }

      span {
        font-size: 38px;
        margin-left: 10px;
        letter-spacing: 5px;
        font-weight: bold;
      }
    }

    .desc {
      color: #eee;
      font-size: 14px;
      letter-spacing: 1px;
      margin-bottom: 50px;
    }

    .el-form {
      width: 300px;

      :deep(.el-form-item) {
        margin-bottom: 20px;

        .el-form-item__label {
          color: #ccc;
        }
      }

      input {
        background-color: transparent;
        color: #fff;
        border: 0;
        height: 40px;
        width: calc(100% - 4px);
        margin: 0 2px;
        padding: 0 2px;
        box-sizing: border-box;
        -webkit-text-fill-color: #fff;
        font-size: 15px;
        border-bottom: 1px solid rgba(255, 255, 255, 0.5);
        border-radius: 0;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px transparent inset !important;
          transition: background-color 50000s ease-in-out 0s;
        }

        &::-webkit-input-placeholder {
          font-size: 12px;
        }

        &:focus {
          border-bottom: 1px solid #fff;
          outline: none;
        }
      }

      .row {
        display: flex;
        align-items: center;
        width: 100%;
        position: relative;

        .captcha-code {
          position: absolute;
          right: 0;
          bottom: 1px;
          height: 40px;
          background-color: #fff;
        }
      }

      .keep-login {
        color: #fff;
      }
    }

    .op {
      display: flex;
      justify-content: center;
      margin-top: 50px;

      :deep(.el-button) {
        height: 40px;
        width: 140px;
        font-size: 15px;
      }
    }
  }
}
</style>
